package com.dlm.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dlm.dao.HisAddress;
import com.dlm.dao.Order;
import com.dlm.dao.OrderItem;
import com.dlm.dao.WorkTime;
import com.dlm.service.IOrderService;
import com.dlm.service.IUserCouponService;
import com.dlm.service.impl.OrderServiceImpl;
import com.dlm.service.impl.UserCouponServiceImpl;
import com.dlm.util.TypeUtil;
import com.google.common.base.Preconditions;
import com.jfinal.plugin.activerecord.Page;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import java.util.List;

/**
 * Created by chongsong on 15/2/1.
 * <mailto>chong.song@autonavi.com</mailto>
 */
public class OrderController extends BaseController {
    private Logger logger = Logger.getLogger(OrderController.class);
    private IOrderService orderService = new OrderServiceImpl();
    private IUserCouponService userCouponService = new UserCouponServiceImpl();

    public void add() {
        if(getSession().getAttribute("openid") == null){
            renderJson(makeDto(100,"请先登录!" , null));
            return;
        }
        long techId = getParaToLong("techId", 0l);
        String beginTime = getPara("beginTime");
        String address = getPara("address");
        int isMyself = getParaToInt("isMyself", 1);
        String sumPrice = getPara("sumPrice");
        int isCoupon = getParaToInt("isCoupon", 0);
        String couponPrice = getPara("couponPrice");
        String cashPrice = getPara("cashPrice");
        String items = getPara("items");
        String beginDate = getPara("beginDate");
        int couponId = getParaToInt("couponId", 0);
        int payWay = getParaToInt("payWay", 0);
        try {
            Preconditions.checkArgument((techId > 0), "techId不能为空,且必须为整数");
            Preconditions.checkArgument(StringUtils.isNotBlank(beginTime), "beginTime不能为空!");
            Preconditions.checkArgument(StringUtils.isNotBlank(beginDate), "beginDate不能为空!");
            Preconditions.checkArgument(StringUtils.isNotBlank(address), "address不能为空!");
            Preconditions.checkArgument((isMyself > 0), "isMyself不能为空,且必须为0或1!");
            Preconditions.checkArgument(TypeUtil.isDouble(sumPrice), "sumPrice不能为空,且必须为数字!");
            Preconditions.checkArgument((isCoupon >= 0), "isCoupon不能为空,且必须为0或1!");
            Preconditions.checkArgument(TypeUtil.isDouble(couponPrice), "couponPrice不能为空,且必须为数字!");
            Preconditions.checkArgument(TypeUtil.isDouble(cashPrice), "cashPrice不能为空,且必须为数字!");
            Preconditions.checkArgument(StringUtils.isNotBlank(items), "items不能为空!");
        } catch (Exception e) {
            renderJson(makeDto(1, e.getMessage(), null));
            return;
        }
        Order order = new Order();
        order.set(Order.techId, techId);
        order.set(Order.beginTime, beginTime);
        order.set(Order.beginDate, beginDate);
        order.set(Order.openid, getSession().getAttribute("openid"));
        order.set(Order.isMyself, isMyself);
        order.set(Order.sumPrice, sumPrice);
        order.set(Order.isCoupon, isCoupon);
        order.set(Order.couponPrice, couponPrice);
        order.set(Order.cashPrice, cashPrice);
        order.set(Order.payWay, payWay);
        boolean isSave = false;
        try {
            isSave = orderService.add(order);
            JSONArray arrays = JSON.parseArray(items);
            if (arrays != null && arrays.size() > 0) {
                for (Object obj : arrays) {
                    JSONObject jObj = (JSONObject) obj;
                    OrderItem oi = new OrderItem();
                    oi.set(OrderItem.itemId, jObj.get("item_id"));
                    oi.set(OrderItem.num, jObj.get("num"));
                    oi.set(OrderItem.orderId, order.get("id"));
                    oi.set(OrderItem.sumPrice, jObj.get("sumPrice"));
                    oi.save();
                }
            }
            System.out.println(address);
            JSONObject addressObj = JSON.parseObject(address);
            if (addressObj != null) {
                String city = addressObj.getString("cityName");
                String dict = addressObj.getString("dictName");
                String addr = addressObj.getString("address");
                if(!addr.contains(city)){
                    addr = city + " " + dict + " " + addr;
                }
                HisAddress ha = new HisAddress();
                ha.set(HisAddress.name, addressObj.get("contact"));
                ha.set(HisAddress.address, addr);
                ha.set(HisAddress.remark, addressObj.get("remark"));
                ha.set(HisAddress.tel, addressObj.get("phone"));
                ha.set(HisAddress.openid, getSession().getAttribute("openid"));
                ha.set(HisAddress.orderId, order.get(Order.id));
                ha.save();
            }
            //下单成功, 设置优惠券为使用过状态,并发送短信.
            if (isSave) {
                if(couponId > 0){
                    userCouponService.useCoupon(couponId);
                }
                orderService.sendOrderSMS(order.getLong(Order.id));
                renderJson(makeDto(0, "ok", null));
                return;
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        renderJson(makeDto(1, "保存失败!", null));
    }

    public void cancelOrder(){
        long id = getParaToLong("id", 0l);
        String openid = (String)getSession().getAttribute("openid");
        try {
            Preconditions.checkArgument(StringUtils.isNotBlank(openid), "用户未登陆!");
            Preconditions.checkArgument(id > 0, "id不能为空且必须大于0!");
            orderService.cancel(id);
            orderService.sendOrderCancelSMS(id);
            renderJson(makeDto(0, "ok", null));
        } catch (Exception e) {
            renderJson(makeDto(1, e.getMessage(), null));
        }
    }

    public void del() {
        long id = getParaToLong("id", 0l);
        String openid = (String)getSession().getAttribute("openid");
        try {
            Preconditions.checkArgument(StringUtils.isNotBlank(openid), "用户未登陆!");
            Preconditions.checkArgument(id > 0, "id不能为空且必须大于0!");
        } catch (Exception e) {
            renderJson(makeDto(1, e.getMessage(), null));
            return;
        }

        boolean isDel = false;
        try {
            isDel = orderService.delete(id);
            if (isDel) {
                renderJson(makeDto(0, "ok", null));
                return;
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        renderJson(makeDto(1, "删除失败", null));
    }

    public void find() {
        int pno = getParaToInt("pno", 1);
        int psize = getParaToInt("psize", 10);
        String openid = (String)getSession().getAttribute("openid");
        try {
            if(StringUtils.isBlank(openid)){
                renderJson(makeDto(100,"请先登录!" , null));
                return;
            }
            if(null == getSession().getAttribute("phone")){
                renderJson(makeDto(100, "查询失败", null));
                return;
            }
            Page<Order> page = orderService.findByPage(openid,pno, psize);
            renderJson(makeDtoPage(0, "ok", page));
            return;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        renderJson(makeDto(1, "查询失败", null));
    }

    public void findById() {
        long orderId = getParaToLong("orderId", 0l);
        String openid = (String)getSession().getAttribute("openid");
        try {
            Preconditions.checkArgument((orderId > 0), "orderId不能为空,且必须为整数");
            if(StringUtils.isBlank(openid)){
                renderJson(makeDto(100,"请先登录!" , null));
                return;
            }
            Order order = orderService.findById(orderId);
            renderJson(makeDto(0, "ok", order));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            renderJson(makeDto(1, e.getMessage(), null));
        }
    }

    public void findWT() {
        long techId = getParaToLong("techId", 0L);
        String date = getPara("date");
        try {
            Preconditions.checkArgument((techId > 0), "techId必须为正整数!");
            Preconditions.checkArgument(StringUtils.isNotBlank(date), "date不能为空!");
            List<Order> wt = orderService.findWT(techId, date);
            if (wt == null) {
                throw new Exception("查询失败! " + techId + "  " + date);
            }
            renderJson(makeDtoList(0, "ok", wt));
        } catch (Exception e) {
            renderJson(makeDto(1, e.getMessage(), null));
        }
    }

    public void findAllWT() {
        try {
            List<WorkTime> wt = orderService.findAllWT();
            if (wt == null) {
                throw new Exception("查询失败! ");
            }
            renderJson(makeDtoList(0, "ok", wt));
        } catch (Exception e) {
            renderJson(makeDto(1, e.getMessage(), null));
        }
    }
}
